package com.hmdp.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    CacheClient cacheClient;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Result queryId(Long id) {

       // 解决缓存穿透代码（建立空缓存）
     //   Shop shop = queryWithPassThrough(id);
        //解决缓存击穿代码(基于互斥锁)
      //   Shop shop =  queryWithMutex(id);

        /*Shop shop = cacheClient
                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);*/
    // 逻辑过期解决缓存击穿
        /* Shop shop = cacheClient
                 .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);*/
        Shop shop = cacheClient
                .queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);

         if (shop == null) {
             shop = new Shop();
         }
       return Result.ok(shop);
    }

    /**
     * 解决缓存穿透代码（建立空缓存）
     * @param id
     * @return
     */
    public Result queryWithPassThrough(Long id) {
        String key=CACHE_SHOP_KEY+id;
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)){//缓存存在，即直接返回
            if (Objects.equals(value, "null")) {//判断是不是空缓存(即缓存穿透)
                return Result.fail("店铺不存在！");
            }
            Shop shop = JSONUtil.toBean(value, Shop.class);
            return Result.ok(shop);
        }

        //没有在缓存中 根据id查
        Shop shop = this.getById(id);
        if (shop==null){
            //避免缓存穿透，设置reids空缓存
            stringRedisTemplate.opsForValue().set(key,"null",CACHE_NULL_TTL, TimeUnit.MINUTES);

            return Result.fail("店铺不存在！");
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    /**
     * 解决缓存击穿代码(基于互斥锁)  [注：包含了缓存穿透的解决方案]
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        String key=CACHE_SHOP_KEY+id;
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)){//缓存存在，即直接返回
            if (Objects.equals(value, "null")) {//判断是不是空缓存(即缓存穿透)
                return null;
            }
            Shop shop = JSONUtil.toBean(value, Shop.class);
            return shop;
        }

        String lockkey= null;
        Shop shop = null;
        try {
            lockkey = LOCK_SHOP_KEY+id;
            if (!this.tryLock(lockkey)) {//如果没有获取到锁
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //没有在缓存中 根据id查
            shop = this.getById(id);
            if (shop==null){
                //避免缓存穿透，设置reids空缓存
                stringRedisTemplate.opsForValue().set(key,"null",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unLock(lockkey);
        }
        return shop;
    }


    /**
     * 加锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "lock", 10, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(b);
    }

    /**
     * 释放锁
     * @param key
     * @return
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);

    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    /**
     *   解决缓存击穿代码(基于设置逻辑过期)
     * @param id
     * @return
     */
    public Shop queryWithLogicExpire(Long id) {
        String key=CACHE_SHOP_KEY+id;
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(value)){//如果热点缓存不存在，即直接返回找不到 →→→
           return null;
        }

        //缓存命中↓↓↓
        RedisData redisData = JSONUtil.toBean(value, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){        //判断是否缓存过期
            //如果没有过期
            return shop;
        }

        //如果过期
        String lockkey=LOCK_SHOP_KEY+id;
        if (this.tryLock(lockkey)){//判断是否获取锁
            //如果有锁 开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try{
                    //重建缓存
                    this.saveToRedis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    this.unLock(lockkey);
                }
            });
        }

        return shop;
    }



    /**
     * 缓存预热（预热信息）
     * @param id
     * @param expireSeconds
     */
    public void saveToRedis(Long id,Long expireSeconds) {
        Shop shop = this.getById(id);
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));

    }



    /**
     * 更新操作
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updates(Shop shop) {
        if (shop.getId()==null){
            return Result.fail("店铺不存在！");
        }
        //1、更新数据库
        this.updateById(shop);
        //2、更新删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }
}
